/**
 * 用户路由模块
 */
const express = require("express");
const { check, query, body } = require("express-validator");
const { login, logout, register, resetPassword } = require("../services/userService");
const router = express.Router();
const { poolPromise } = require("../db/index");

/**
 * 用户登录
 */
router.post(
  "/login",
  [
    body("username").notEmpty().escape().withMessage("用户名不能为空"),
    body("password")
      .notEmpty()
      .withMessage("密码不能为空")
      .isLength({ min: 6 })
      .withMessage("密码长度至少为6位")
      .escape(),
  ],
  login
);

/**
 * 登出成功
 */
router.post("/logout", logout);

/**
 * 用户注册
 */
router.post(
  "/register",
  [
    body("username").notEmpty().escape().withMessage("用户名不能为空"),
    body("password").notEmpty().escape().withMessage("密码不能为空"),
  ],
  register
);

/**
 * 重置密码
 */
router.patch(
  "/resetPassword",
  [
    body("username").notEmpty().escape().withMessage("用户名不能为空"),
    body("oldPassword").notEmpty().escape().withMessage("旧密码不能为空"),
    body("newPassword").notEmpty().escape().withMessage("新密码不能为空"),
  ],
  resetPassword
);

/**
 * 获取用户信息
 */
router.get("/info", async (req, res, next) => {
  try {
    let { user_id } = req.auth;
    const sql = `select username,nickname,avatar,sex,age,address,phone,email,state,create_time,login_time,update_time from user where id = ?`;
    let [result] = await poolPromise.query(sql, [user_id]);
    if (!result.length) {
      return res.status(200).json({
        code: 200,
        msg: "获取用户信息失败",
        data: null,
      });
    }
    let {
      username,
      nickname,
      avatar,
      sex,
      age,
      address,
      phone,
      email,
      state,
      create_time,
      login_time,
      update_time,
    } = result[0];

    res.status(200).json({
      code: 200,
      msg: "获取用户信息成功",
      data: {
        id: user_id,
        username,
        nickname,
        avatar,
        sex,
        age,
        address,
        phone,
        email,
        state,
        create_time,
        login_time,
        update_time,
      },
    });
  } catch (error) {
    next(error);
  }
});

/**
 * 修改用户信息
 */
router.put("/info", async (req, res, next) => {
  try {
    let { id, nickname, avatar, sex, age, address, phone, email } = req.body;
    id = 2;
    const sql = `update user set nickname = ?,avatar = ?,sex = ?,age = ?,address = ?,phone = ?,email = ? where id = ?`;
    let [{ affectedRows }] = await poolPromise.execute(sql, [
      nickname,
      avatar,
      sex,
      age,
      address,
      phone,
      email,
      id,
    ]);
    if (!affectedRows) {
      return res.status(409).json({
        code: 409,
        msg: "修改用户信息失败",
        data: null,
      });
    }

    res.status(200).json({
      code: 200,
      msg: "修改用户信息成功",
      data: null,
    });
  } catch (error) {
    next(error);
  }
});

module.exports = router;
